﻿using LocalNas.Application.Service.Wankeyun.Dto;
using WkyApiSharp.Service.Model;
using WkyApiSharp.Service.Model.CreateBatchTaskResult;
using WkyApiSharp.Service.Model.UrlResolve;

namespace LocalNas.Application.Service.Wankeyun;
[ApiDescriptionSettings(ConstSwaggerGroup.NAS平台, Name = "玩客云", Order = 100)]
public class WankeyunService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<SysSetting> _sysSettingRep;
    public WankeyunService(SqlSugarRepository<SysSetting> sysSettingRep)
    {
        if (!GlobalData.WkyInitComplete)
        {
            try
            {
                GlobalData.InitWky().Wait();
            }
            catch (Exception ex)
            {
                throw Oops.Oh(ex.Message);
            }
        }
        _sysSettingRep = sysSettingRep;
    }

    /// <summary>
    /// 获取所有任务
    /// </summary>
    /// <returns></returns>
    [HttpGet("/Wankeyun/GetAllDevice")]
    public async Task<List<WkyDevice>> GetAllDevice()
    {
        await GlobalData.wkyApi.UpdateTask();
        return GlobalData.wkyApi.GetAllDevice();
    }

    /// <summary>
    /// URL解析
    /// </summary>
    /// <param name="request"></param>
    /// <returns></returns>
    [HttpPost("/Wankeyun/UrlResolve")]
    public async Task<WkyApiUrlResolveResultModel> UrlResolve(UrlResolveRequest request)
    {
        var result = await GlobalData.wkyApi.UrlResolve(request.PeerId, request.Url);
        if (result.Rtn != 0) throw Oops.Oh(result.Msg);
        return result;
    }


    /// <summary>
    /// 根据链接解析结果 下载勾选的文件
    /// </summary>
    /// <param name="request"></param>
    /// <returns></returns>
    [HttpPost("/Wankeyun/CreateBatchTaskWithUrlResolve")]
    public async Task<WkyApiCreateBatchTaskResultModel> CreateBatchTaskWithUrlResolve(CreateBatchTaskWithUrlResolveRequest request)
    {
        var result = await GlobalData.wkyApi.CreateBatchTaskWithUrlResolve(request.PeerId, request.Path, request.UrlResolveResult, request.SubTaskId);
        if (result.Rtn != 0) throw Oops.Oh(result.Msg);
        await GlobalData.wkyApi.UpdateTask();
        return result;
    }

    /// <summary>
    /// 暂停任务
    /// </summary>
    /// <param name="request"></param>
    /// <returns></returns>
    [HttpPost("/Wankeyun/PauseTask")]
    public async Task<bool> PauseTask(HandleTaskResult request)
    {
        var result = await GlobalData.wkyApi.PauseTask(request.PeerId, request.TaskId);
        await GlobalData.wkyApi.UpdateTask();
        return result;
    }

    /// <summary>
    /// 开始任务
    /// </summary>
    /// <param name="request"></param>
    /// <returns></returns>
    [HttpPost("/Wankeyun/StartTask")]
    public async Task<bool> StartTask(HandleTaskResult request)
    {
        var result = await GlobalData.wkyApi.StartTask(request.PeerId, request.TaskId);
        await GlobalData.wkyApi.UpdateTask();
        return result;
    }

    /// <summary>
    /// 删除任务
    /// </summary>
    /// <param name="request"></param>
    /// <returns></returns>
    [HttpPost("/Wankeyun/DeleteTask")]
    public async Task<bool> DeleteTask(HandleTaskResult request)
    {
        var result = await GlobalData.wkyApi.DeleteTask(request.PeerId, request.TaskId, request.DeleteFile);
        await GlobalData.wkyApi.UpdateTask();
        return result;
    }



    //public async void Test()
    //{
    //    //  DateTimeOffset.Now.ToUnixTimeMilliseconds()/1000
    //    //var sign = GenAuthorization(new
    //    //{
    //    //    ct = 0,
    //    //    id = "RD_00001",
    //    //    pid = "fef03805c6f0f4d04300e8babb6c9a22",
    //    //    ts = Math.Floor(DateTimeOffset.Now.ToUnixTimeMilliseconds() / 1000m),
    //    //    v = 2
    //    //});

    //    //var a = await UrlResolve("magnet:?xt=urn:btih:8C3FC38A510277CE3EAAB8CB2A1E7CCFC7C2BBEB");
    //}

    //public async Task<UrlResolveResult> UrlResolve(string url)
    //{
    //    var timestep = DateTimeOffset.Now.ToUnixTimeMilliseconds();
    //    var time = Math.Floor(timestep / 1000m);
    //    var pid = MD5Encryption.Encrypt(timestep.ToString());
    //    var sign = GenAuthorization(new
    //    {
    //        ct = 0,
    //        id = "RD_00001",
    //        pid = pid,
    //        ts = time,
    //        v = 2
    //    });

    //    var result = await $"https://control-remotedl.onethingpcs.com/other/urlResolve?pid={pid}&v=2&ct=0&sign={sign}"
    //    .SetHeaders(new
    //    {
    //        //origin = "https://h5-ocapp.onethingpcs.com",
    //        //referer = "https://h5-ocapp.onethingpcs.com/vPages/webapp/",
    //        authorization = $"id=RD_00001,ts={time}",
    //        cookie = ""
    //    })
    //    .SetHttpMethod(HttpMethod.Post)
    //    .SetBody(new
    //    {
    //        url = url
    //    }, "application/x-www-form-urlencoded")
    //    .PostAsAsync<UrlResolveResult>();

    //    return result;

    //}


    //public string GenAuthorization(dynamic data)
    //{
    //    var key = "we23edscvfr45tgb6yhn";
    //    var str = "";
    //    var arr = new List<string>();
    //    foreach (PropertyInfo item in data.GetType().GetProperties())
    //    {
    //        arr.Add(item.Name);
    //    }
    //    if (arr.Count > 0)
    //    {
    //        arr.Sort();
    //        for (int i = 0; i < arr.Count; i++)
    //        {
    //            var value = data.GetType().GetProperty(arr[i].ToString()).GetValue(data, null);
    //            if (value.ToString() != "")
    //            {
    //                str += arr[i].ToString() + "=" + value + "&";
    //            }
    //        }
    //    }
    //    return MD5Encryption.Encrypt(str.Substring(0, str.Length - 1) + "&key=" + key);
    //}
}
